<link rel="import" href="../../bower_components/polymer/polymer-element.html">
<link rel="import" href="../../bower_components/vaadin-material-theme/vaadin-grid.html">
<link rel="import" href="../../bower_components/vaadin-material-theme/vaadin-grid-selection-column.html">
<link rel="import" href="../view-app.html">
<link rel="import" href="../style/shared-styles.html">

<dom-module id="view-setup-customer">
    <template>
        <style include="shared-styles app-grid-style flat-button">
            :host {
                margin: 10px;
                display: block;
                --app-grid-columns: 1;
            }

            .btn {
                width: 250px;
            }

            .details {
                padding: 10px;
            }
        </style>
        <firebase-auth app-name="smart-mes" id="auth" user="{{user}}"></firebase-auth>
        <firebase-document app-name="smart-mes" id="userData" path="/user/[[user.uid]]" data="{{k}}"></firebase-document>
        <firebase-query app-name="smart-mes" id="customerQuery" path="/data/[[k.key]]/factoryData/customer" order-by-child="fname" data="{{customerData}}"></firebase-query>
        <firebase-document app-name="smart-mes" id="editCustomerQuery" path="/data/[[k.key]]/factoryData/customer/[[editKey]]" data="{{editCustomerData}}"></firebase-document>
        <app-localstorage-document key="app-lang" data="{{language}}"></app-localstorage-document>
        <ul class="app-grid">
            <li>
                <div class="card" hidden="[[!showAddCustomer]]">
                    <h1 class="title">{{localize('add-customer')}}</h1>
                    <paper-input label="{{localize('first-name')}}" id="customerFirstName" max-length="40" type="text" auto-validate allowed-pattern="[a-zA-Z]"
                        error-message="Text only" always-float-label></paper-input>
                    <paper-input label="{{localize('last-name')}}" id="customerLastName" max-length="40" type="text" auto-validate allowed-pattern="[a-zA-Z]"
                        error-message="Text only" always-float-label></paper-input>
                    <paper-input label="{{localize('email')}}" id="customerEmail" max-length="40" type="email" auto-validate error-message="invalid input"
                        always-float-label>
                    </paper-input>
                    <paper-input label="{{localize('mobile')}}" id="customerMobile" max-length="10" type="tel" auto-validate allowed-pattern="^(0|[1-9]\d*)$"
                        error-message="Number only" always-float-label></paper-input>
                    <paper-input label="{{localize('address')}}" id="customerAddress" max-length="200" type="text" auto-validate error-message="text only"
                        always-float-label></paper-input>
                    <div class="center">
                        <flat-button class="btn" on-click="_openCustomerTable">
                            <button>{{localize('dismiss')}}</button>
                        </flat-button>
                        <flat-button class="btn shamrock" on-click="addCustomer">
                            <button disabled$="[[disabled]]">{{localize('add')}}</button>
                        </flat-button>
                    </div>
                </div>
            </li>
            <li>
                <div class="card" hidden="[[!showEditCustomer]]">
                    <h1 class="title">{{localize('edit-customer')}}</h1>
                    <paper-input label="{{localize('first-name')}}" id="edit_customerFirstName" max-length="40" type="text" value="[[getNamePosition(editCustomerData.name, 0)]]"
                        auto-validate allowed-pattern="[a-zA-Z]" error-message="text only" always-float-label></paper-input>
                    <paper-input label="{{localize('last-name')}}" id="edit_customerLastName" max-length="40" type="text" value="[[getNamePosition(editCustomerData.name, 1)]]"
                        auto-validate allowed-pattern="[a-zA-Z]" error-message="text only" always-float-label></paper-input>
                    <paper-input label="{{localize('email')}}" id="edit_customerEmail" max-length="40" type="email" value="[[editCustomerData.email]]"
                        auto-validate error-message="Invalid input" always-float-label>
                    </paper-input>
                    <paper-input label="{{localize('mobile')}}" id="edit_customerMobile" max-length="10" type="tel" value="[[editCustomerData.mobile]]"
                        auto-validate error-message="Number only" always-float-label></paper-input>
                    <paper-input label="{{localize('address')}}" id="edit_customerAddress" max-length="200" type="text" value="[[editCustomerData.address]]"
                        auto-validate error-message="Text only" always-float-label></paper-input>
                    <div class="center">
                        <flat-button class="btn" on-click="_openCustomerTable">
                            <button>{{localize('dismiss')}}</button>
                        </flat-button>
                        <flat-button class="btn shamrock" on-click="saveCustomer">
                            <button disabled$="[[disabled]]">{{localize('save')}}</button>
                        </flat-button>
                    </div>
                </div>
            </li>
            <li>
                <div class="card" hidden="[[!showListCustomer]]">
                    <h1 class="title">{{localize('customer-management')}}</h1>
                    <vaadin-grid id="customerTable" aria-label="Customer Management" items="[[customerData]]" selected-items="{{selectedItem}}">
                        <vaadin-grid-selection-column flex="1" select-all="{{selectAll}}">
                            <template class="header">
                                <paper-checkbox checked="{{selectAll}}"></paper-checkbox>
                            </template>
                            <template>
                                <paper-checkbox checked="{{selected}}"></paper-checkbox>
                            </template>
                        </vaadin-grid-selection-column>

                        <vaadin-grid-column flex-grow="2" flex="1">
                            <template class="header">
                                <div class="cell">{{localize('first-name')}}</div>
                            </template>
                            <template>
                                <div class="cell">[[item.name]]</div>
                            </template>
                        </vaadin-grid-column>

                        <vaadin-grid-column flex-grow="2" flex="1">
                            <template class="header">
                                <div class="cell">{{localize('email')}}</div>
                            </template>
                            <template>
                                <div class="cell">[[item.email]]</div>
                            </template>
                        </vaadin-grid-column>

                        <vaadin-grid-column flex-grow="2" flex="1">
                            <template class="header">
                                <div class="cell">{{localize('mobile')}}</div>
                            </template>
                            <template>
                                <div class="cell">[[item.mobile]]</div>
                            </template>
                        </vaadin-grid-column>

                        <vaadin-grid-column flex="1">
                            <template class="header">
                                <div class="cell">{{localize('detail')}}</div>
                            </template>
                            <template>
                                <paper-checkbox aria-label$="Show Details for [[item.name]]" checked="{{detailsOpened}}"></paper-checkbox>
                            </template>
                        </vaadin-grid-column>

                        <vaadin-grid-column flex="1">
                            <template class="header">
                                <div class="cell last">{{localize('edit')}}</div>
                            </template>
                            <template>
                                <div class="cell last">
                                    <paper-icon-button on-click="_openEditCustomerCard" customer="[[item]]" icon="vaadin:pencil" title="Edit"></paper-icon-button>
                                </div>
                            </template>
                        </vaadin-grid-column>

                        <vaadin-grid-column flex="1">
                            <template class="header">
                                <div class="cell last">{{localize('delete')}}</div>
                            </template>
                            <template>
                                <div class="cell last">
                                    <paper-icon-button on-click="deleteCustomer" customer="[[item]]" icon="vaadin:trash" title="Delete"></paper-icon-button>
                                </div>
                            </template>
                        </vaadin-grid-column>

                        <!-- Row detail -->
                        <template class="row-details">
                            <div class="details">
                                <div flex="1">
                                    <h4>{{localize('address')}}</h4>
                                    <p>[[item.address]]</p>
                                </div>
                            </div>
                        </template>
                    </vaadin-grid>
                    <div class="center">
                        <flat-button class="btn" on-click="_openAddCustomerCard">
                            <button>{{localize('add-customer')}}</button>
                        </flat-button>
                    </div>
                </div>
            </li>
        </ul>
        <paper-toast id="toastAlert" always-on-top horizontal-align="right" text="{{localize(toastText)}}"></paper-toast>
    </template>
    <script>
        /**
         * @ViewSetupCustomer
         * @polymer 
         * @extends {Polymer.Element}
         */
        class ViewSetupCustomer extends Polymer.mixinBehaviors([Polymer.AppLocalizeBehavior],
            Polymer.Element) {
            static get is() {
                return 'view-setup-customer'
            }

            static get properties() {
                return {
                    language: String,
                    editKey: String,
                    customerData: Object,
                    selectedItem: Object,
                    editCustomerData: Object,
                    selectAll: Boolean,
                    toastText: String,
                    disabled: {
                        type: Boolean,
                        value: true
                    },
                    showAddCustomer: {
                        type: Boolean,
                        value: false
                    },
                    showEditCustomer: {
                        type: Boolean,
                        value: false
                    },
                    showListCustomer: {
                        type: Boolean,
                        value: true
                    },
                }
            }

            connectedCallback() {
                super.connectedCallback()
                this.loadResources(this.resolveUrl('../../data/locales.json'))
            }

            ready() {
                super.ready()
                requestAnimationFrame(this._installListeners.bind(this))
            }

            _installListeners() {
                this.$.customerFirstName.addEventListener('input', this._validateInput.bind(this))
                this.$.customerLastName.addEventListener('input', this._validateInput.bind(this))
                this.$.customerEmail.addEventListener('input', this._validateInput.bind(this))
                this.$.customerMobile.addEventListener('input', this._validateInput.bind(this))
                this.$.customerAddress.addEventListener('input', this._validateInput.bind(this))
                this.$.edit_customerFirstName.addEventListener('input', this._validateEditInput.bind(this))
                this.$.edit_customerLastName.addEventListener('input', this._validateEditInput.bind(this))
                this.$.edit_customerEmail.addEventListener('input', this._validateEditInput.bind(this))
                this.$.edit_customerMobile.addEventListener('input', this._validateEditInput.bind(this))
                this.$.edit_customerAddress.addEventListener('input', this._validateEditInput.bind(this))
            }

            _validateInput() {
                const fname = this.$.customerFirstName.value
                const lname = this.$.customerLastName.value
                const email = this.$.customerEmail.value
                const mobile = this.$.customerMobile.value
                const address = this.$.customerAddress.value
                if (fname && lname && email && mobile && this.$.customerEmail.validate() && address) {
                    this.disabled = false
                } else {
                    this.disabled = true
                }
            }

            _validateEditInput() {
                const fname = this.$.edit_customerFirstName.value
                const lname = this.$.edit_customerLastName.value
                const email = this.$.edit_customerEmail.value
                const mobile = this.$.edit_customerMobile.value
                const address = this.$.edit_customerAddress.value
                if (fname && lname && email && mobile && this.$.customerEmail.validate() && address) {
                    this.disabled = false
                } else {
                    this.disabled = true
                }
            }

            _openEditCustomerCard(e) {
                this.showEditCustomer = true
                this.showListCustomer = false
                const key = e.currentTarget.customer.$key
                this.editKey = key
            }

            _openAddCustomerCard() {
                this.showAddCustomer = true
                this.showListCustomer = false
            }

            _openCustomerTable() {
                this.showListCustomer = true
                this.showAddCustomer = false
                this.showEditCustomer = false
                this._clearField()
            }

            _clearField() {
                this.$.customerFirstName.value = ""
                this.$.customerLastName.value = ""
                this.$.customerEmail.value = ""
                this.$.customerMobile.value = ""
                this.$.customerAddress.value = ""
                this.editKey = ""
            }

            addCustomer() {
                const fname = this.$.customerFirstName.value
                const lname = this.$.customerLastName.value
                const fullname = fname + ' ' + lname
                const email = this.$.customerEmail.value
                const mobile = this.$.customerMobile.value
                const address = this.$.customerAddress.value
                const mobileHyphens = mobile.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3")
                const timestamp = Math.round(Date.now() / 1000.0)
                if (fullname && email && mobile && address) {
                    this.$.customerQuery.ref.push({
                        name: fullname,
                        email: email,
                        address: address,
                        mobile: mobileHyphens,
                        created: timestamp
                    });
                    this._clearField();
                    this.toastText = 'notification-add-successfully'
                    this.$.toastAlert.open()
                    this._openCustomerTable()
                } else {
                    this.toastText = 'notification-error-incomplete-input'
                    this.$.toastAlert.open()
                }
            }

            deleteCustomer(e) {
                if (window.confirm("Delete this customer ?") == true) {
                    let key = e.currentTarget.customer.$key
                    this.$.customerQuery.ref.child(key).remove()
                    this.toastText = 'notification-delete-successfully'
                    this.$.toastAlert.open();
                }
            }

            saveCustomer() {
                const fname = this.$.edit_customerFirstName.value
                const lname = this.$.edit_customerLastName.value
                const fullname = fname + ' ' + lname
                const email = this.$.edit_customerEmail.value
                const mobile = this.$.edit_customerMobile.value
                const address = this.$.edit_customerAddress.value
                const mobileHyphens = mobile.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3")

                if (fullname && email && mobile && address) {
                    this.$.editCustomerQuery.ref.update({
                        name: fullname,
                        email: email,
                        address: address,
                        mobile: mobileHyphens
                    });
                    this.toastText = 'notification-save-successfully'
                    this.$.toastAlert.open()
                    this._openCustomerTable()
                } else {
                    this.toastText = 'notification-error-incomplete-input'
                    this.$.toastAlert.open()
                }
            }

            getNamePosition(name, index) {
                if (!name) return
                return name.split(' ')[index]
            }
        }
        customElements.define(ViewSetupCustomer.is, ViewSetupCustomer)
    </script>
</dom-module>